<?php

namespace Home\Controller;

class DogController extends BaseController {

    public function _initialize() {
        $userToken = '';
        if (I("user_token")) {
            $userToken = I("user_token");
        }
        //查询库
        $where['user_token'] = $userToken;
        $userTokenInfo = M('Users')->where($where)->find();
        if ($userTokenInfo) {
            $this->user_id = $userTokenInfo['user_id'];
        }
    }

    public function getList() {
//        if ($this->user_id == 0) {
//            $this->error('请登录', '', 101);
//        }

        $user_id = I('user_id', 0, 'intval');

        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }


        $where['user_id'] = $this->user_id;
        $where['is_del'] = 0;
        $where['status'] = 0;

        if ($user_id != 0) {
            $where['user_id'] = $user_id;
        }


        $list = M('Dog')
                ->where($where)
                ->limit($page, $size)
                ->order('create_time desc')
                ->select();

        if ($list) {
            foreach ($list as &$val) {
                if ($val['dog_face']) {
                    $val['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['dog_face'];
                }

                $val['xz'] = birthext($val['dog_brithday']);
                $age = birthday($val['dog_brithday']);

                $age_str = '';
                if ($age < 1) {
                    $age = $age * 10;
                    $age_str = $age . '个月';
                } else {
                    $age = floor($age);
                    $age_str = $age . '周岁';
                }
                $val['age'] = $age_str;
                $yuanbao_sum = M('Reward')->where(['dog_id' => $val['dog_id']])->sum('number');
                if (empty($yuanbao_sum)) {
                    $val['yuanbao_sum'] = 0;
                } else {
                    $val['yuanbao_sum'] = $yuanbao_sum;
                }
            }

            unset($val);
        } else {
            $list = [];
        }


        $this->success('获取成功', $list);
    }

    public function getMyDog() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }
        $list = M('Dog')
                ->field('dog_id,dog_name')
                ->where(['user_id' => $this->user_id, 'is_del' => 0])
                ->order('create_time desc')
                ->select();
        $this->success('获取成功', $list);
    }

    public function addOrEdit() {

        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }
        $is_edit = I('is_edit', 0, 'intval');
        $dog_id = I('dog_id', 0, 'intval');

        $dog_name = I('dog_name');
        $dog_face = I('dog_face');
        $dog_brithday = I('dog_brithday', '2017-10-01');
        $dog_weight = I('dog_weight');

        $describe = I('describe');

        if (empty($dog_name)) {
            $this->error('请输入狗的名字');
        }
        if (empty($dog_face)) {
            $this->error('请上传头像');
        }

        if (!strtotime($dog_brithday)) {
            $this->error('生日格式不正确');
        }

        if (empty($describe)) {
            $this->error('请输入描述');
        }

        $province = I('province');
        $city = I('city');
        $district = I('district');

        if (empty($province)) {
            $this->error('请选择省');
        }
        if (empty($city)) {
            $this->error('请选择市');
        }
        if (empty($district)) {
            $this->error('请选择区/县');
        }

        $data['dog_name'] = $dog_name;
        $data['dog_face'] = $dog_face;
        $data['dog_brithday'] = $dog_brithday;
        $data['dog_weight'] = $dog_weight;
        $data['describe'] = I('describe');
        $data['dog_sex'] = I('dog_sex', 1, 'intval');
        $data['is_ster'] = I('is_ster', 0, 'intval');
        $data['user_id'] = $this->user_id;

        $data['province'] = $province;
        $data['city'] = $city;
        $data['district'] = $district;

        $data['update_time'] = date('Y-m-d H:i:s', time());

        if ($is_edit) {
            if ($dog_id == 0) {
                $this->error('请选择需要修改的狗卡');
            }
            $res = M('Dog')->where(['dog_id' => $dog_id])->save($data);
        } else {
            $data['card_number'] = substr(time(), 7, 3) . '20' . mt_rand(100, 999);

            $dog_id = M('Dog')->add($data);

            $res = $dog_id;
        }


        $info = M('Dog')->field('dog_id,card_number,dog_name,dog_face,dog_sex,dog_brithday,dog_weight,describe,is_ster,qcode')->where(['dog_id' => $dog_id])->find();

        $card_number = $info['card_number'];
        $dog_face = $info['dog_face'];

        $qcode['qcode'] = '/Uploads/Qcode/' . $card_number . '.png';

        $newFilePath = './Uploads/Qcode/' . $card_number . ".png";

        $this->getQcode($newFilePath, $dog_face, $dog_id, $is_edit);

//        $this->getDogCard($info, $newFilePath);

        $qcode['share_img'] = $this->getDogCard($info, $newFilePath);

        M('Dog')->where(['dog_id' => $dog_id])->save($qcode);

        if ($info['dog_face']) {
            $info['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $info['dog_face'];
        }


        if ($res) {

            unset($info['dog_sex']);
            unset($info['dog_brithday']);
            unset($info['dog_weight']);
            unset($info['describe']);
            unset($info['is_ster']);
            $this->success('操作成功', $info);
        } else {
            $this->error();
        }
    }

    public function getQcode($newFilePath, $dog_face, $dog_id, $is_edit = 0) {

        if ($is_edit == 0) {
            $access_token = S('access_token');
            if (!$access_token) {
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx30752703b6104080&secret=662313ab979c197f150eece00a3bfeef";
                $res = json_decode(file_get_contents($url));
                $access_token = $res->access_token;
                if ($access_token) {
                    S('access_token', $access_token, 7000);
                }
            }

            $getUlr = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;

//        $getUlr = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" . $access_token;
            $toPage = 'pages/dcDetails/dcDetails?id=' . $dog_id . '&shars=1';

//        echo $getUlr;die;
            $data['path'] = $toPage;

            $res = $this->post($getUlr, json_encode($data));


            file_put_contents($newFilePath, $res);
        }

//        $src_path = yuan_img('.' . $dog_face);
//        watermarklogo($newFilePath, $src_path);
    }

    public function post($url, $post_data = '', $timeout = 5) {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, 1);

        if ($post_data != '') {

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        curl_setopt($ch, CURLOPT_HEADER, false);

        $file_contents = curl_exec($ch);

        curl_close($ch);

        return $file_contents;
    }

    public function detail() {
        $dog_id = I('dog_id', 0, 'intval');

        if ($dog_id == 0) {
            $this->error('请选择正确的狗卡');
        }

        $info = M('Dog')->where(['dog_id' => $dog_id, 'is_del' => 0])->find();

        if (empty($info)) {
            $this->error('没有找到该狗卡信息');
        }

        if ($info['dog_face']) {
            $info['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $info['dog_face'];
        }

        if ($info['qcode']) {
            $info['qcode'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $info['qcode'];
        }

        if ($info['share_img']) {
            $info['share_img'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $info['share_img'];
        }

        $info['xz'] = birthext($info['dog_brithday']);
//        $info['age'] = birthday($info['dog_brithday']);
        $age = birthday($info['dog_brithday']);

        $age_str = '';
        if ($age < 1) {
            $age = $age * 10;
            $age_str = $age . '个月';
        } else {
            $age = floor($age);
            $age_str = $age . '周岁';
        }
        $info['age'] = $age_str;
        $info['is_edit'] = 0;
        if (($info['user_id'] == $this->user_id) && $this->user_id != 0) {
            $info['is_edit'] = 1;
        }
        $yuanbao_sum = M('Reward')->where(['dog_id' => $dog_id])->sum('number');
        if (empty($yuanbao_sum)) {
            $info['yuanbao_sum'] = 0;
        } else {
            $info['yuanbao_sum'] = $yuanbao_sum;
        }

        $info['photo_num'] = M('Photo')->where(['dog_id' => $dog_id, 'is_del' => 0])->count();
        $photo_list = M('Photo')->field('photo_id,photo_url')->where(['dog_id' => $dog_id, 'is_del' => 0])->order('create_time desc')->limit(0, 3)->select();

        if (!empty($photo_list)) {
            foreach ($photo_list as &$val) {
                $val['photo_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['photo_url'];
            }

            unset($val);

            $info['photo_list'] = $photo_list;
        } else {
            $info['photo_list'] = [];
        }

        $is_collect = M('DogCollect')->where(['dog_id' => $dog_id, 'user_id' => $this->user_id])->find();

        $info['is_collect'] = 0;
        if ($is_collect) {
            $info['is_collect'] = 1;
        }

        $this->success('获取成功', $info);
    }

    public function getRewardList() {
        $dog_id = I('dog_id', 0, 'intval');

        if ($dog_id == 0) {
            $this->error('请选择正确的狗卡');
        }

        $list = M('Reward')
                ->table('ot_reward r')
                ->field('sum(number) as number,u.head_imgurl,u.nick_name,u.user_id')
                ->join('ot_users u  on r.user_id = u.user_id')
                ->where(['r.dog_id' => $dog_id])
                ->group('u.user_id')
                ->order('sum(number) desc')
                ->select();

        $return_list = [];
        $data = [];
        if (!empty($list)) {
            $i = 1;
            foreach ($list as $val) {
                $val['rank'] = $i;
                $val['is_my_rank'] = 0;
                if ($i <= 10) {
                    $return_list[] = $val;
                }

                if ($val['user_id'] == $this->user_id) {
                    $val['is_my_rank'] = 1;
                    $data[] = $val;
                }

                $i++;
            }
        } else {
            $list = [];
        }

        if (!empty($return_list)) {
            foreach ($return_list as $row) {
                $data[] = $row;
            }
        }



        $this->success('获取成功', $data);
    }

    public function reward() {

        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $dog_id = I('dog_id', 0, 'intval');

        if ($dog_id == 0) {
            $this->error('请选择正确的狗卡');
        }

//        $is_my_dog = M('Dog')->where(['dog_id' => $dog_id, 'user_id' => $this->user_id])->find();
//
//        if ($is_my_dog) {
//            $this->error('不能给自己打赏');
//        }

        $is_reward = M('Reward')->where(['dog_id' => $dog_id, 'user_id' => $this->user_id])->order('create_time desc')->find();

        if ($is_reward) {
            $reward_time = strtotime($is_reward['create_time']);

            if (date('Y-m-d', $reward_time) == date('Y-m-d', time())) {
                $this->error('今天已经打赏过了,请不要重复打赏');
                return;
            }
        }

        $data['dog_id'] = $dog_id;
        $data['user_id'] = $this->user_id;
        $data['number'] = rand(1, 10);

        $res = M('Reward')->add($data);

        $track['relation_id'] = $res;
        $track['dog_id'] = $dog_id;
        $track['type'] = 1;

        M('Track')->add($track);

        if ($res) {

            $info = M('Dog')->field('dog_id,card_number,dog_name,dog_face,dog_sex,dog_brithday,dog_weight,describe,is_ster,qcode')->where(['dog_id' => $dog_id])->find();

            $card_number = $info['card_number'];

            $newFilePath = './Uploads/Qcode/' . $card_number . ".png";

            $qcode['share_img'] = $this->getDogCard($info, $newFilePath);

            M('Dog')->where(['dog_id' => $dog_id])->save($qcode);

            $this->success('打赏成功!', ['number' => $data['number']]);
        } else {
            $this->error('打赏失败!');
        }
    }

    public function collectOrCancel() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $dog_id = I('dog_id', 0, 'intval');

        if ($dog_id == 0) {
            $this->error('请选择正确的狗卡');
        }

        $is_my_dog = M('Dog')->where(['dog_id' => $dog_id, 'user_id' => $this->user_id])->find();

        if ($is_my_dog) {
            $this->error('自己的狗不可以收藏');
        }

        $is_collect = M('DogCollect')->where(['dog_id' => $dog_id, 'user_id' => $this->user_id])->find();

        $res = 0;
        if ($is_collect) {
            $res = M('DogCollect')->where(['collect_id' => $is_collect['collect_id']])->delete();
        } else {
            $data['dog_id'] = $dog_id;
            $data['user_id'] = $this->user_id;
            $res = M('DogCollect')->add($data);
        }

        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function getFamily() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $dogs = M('Dog')->where(['user_id' => $this->user_id, 'is_del' => 0])->getField('dog_id', true);

        $map['p.pro_dog_id'] = array('in', $dogs);

        $map['p.dog_id'] = array('in', $dogs);
        $map['_logic'] = 'or';
        $where['_complex'] = $map;

        $where['p.status'] = 1;

        $family = M('Profess')
                ->table('ot_profess p')
                ->field('p.profess_id,d1.dog_id,d2.dog_id as dog_id2,d1.card_number,d2.card_number as card_number2,d1.dog_name,d2.dog_name as dog_name2,d1.dog_face,d2.dog_face as dog_face2,d1.dog_sex,d2.dog_sex as dog_sex2,d1.is_ster,d2.is_ster as is_ster2,d1.dog_brithday,d2.dog_brithday as dog_brithday2,p.identity')
                ->join('ot_dog d1 on p.dog_id = d1.dog_id')
                ->join('ot_dog d2 on p.pro_dog_id = d2.dog_id')
                ->where($where)
                ->select();

        if (!empty($family)) {
            foreach ($family as &$val) {


                foreach ($dogs as $dog) {
                    if ($val['dog_id'] == $dog) {
                        $val['my_dog_name'] = $val['dog_name'];
                        $val['dog_name'] = $val['dog_name2'];
                        $val['dog_face'] = $val['dog_face2'];
                        $val['card_number'] = $val['card_number2'];
                        $val['dog_sex'] = $val['dog_sex2'];
                        $val['is_ster'] = $val['is_ster2'];
                        $val['dog_brithday'] = $val['dog_brithday2'];
                    }
                    if ($val['dog_id2'] == $dog) {
                        $val['my_dog_name'] = $val['dog_name2'];
                    }
                }
                if ($val['dog_face']) {
                    $val['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['dog_face'];
                }

                $val['xz'] = birthext($val['dog_brithday']);
//                $val['age'] = birthday($val['dog_brithday']);
                $age = birthday($val['dog_brithday']);

                $age_str = '';
                if ($age < 1) {
                    $age = $age * 10;
                    $age_str = $age . '个月';
                } else {
                    $age = floor($age);
                    $age_str = $age . '周岁';
                }
                $val['age'] = $age_str;
            }
            unset($val);
        } else {
            $family = [];
        }


        $collect = M()
                ->table('ot_dog_collect c')
                ->field('d.dog_id,d.card_number,d.dog_name,d.dog_face,d.dog_sex,d.is_ster,d.dog_brithday')
                ->join('ot_dog d on c.dog_id = d.dog_id')
                ->where(['c.user_id' => $this->user_id])
                ->select();

        if (!empty($collect)) {
            foreach ($collect as &$val) {
                if ($val['dog_face']) {
                    $val['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $val['dog_face'];
                }

                $val['xz'] = birthext($val['dog_brithday']);
//                $val['age'] = birthday($val['dog_brithday']);
                $age = birthday($val['dog_brithday']);

                $age_str = '';
                if ($age < 1) {
                    $age = $age * 10;
                    $age_str = $age . '个月';
                } else {
                    $age = floor($age);
                    $age_str = $age . '周岁';
                }
                $val['age'] = $age_str;
            }
            unset($val);
        } else {
            $collect = [];
        }

        $result['family'] = $family;
        $result['collect'] = $collect;

        $this->success('获取成功', $result);
    }

    /**
     * host 生成链接地址
     * level 容错级别 
     * size 图片大小
     */
    public function qrcode($card_number = '', $level = 3, $size = 3) {

        Vendor('phpqrcode');

        $errorCorrectionLevel = intval($level); //容错级别 
        $matrixPointSize = intval($size); //生成图片大小 
        $url = 'https://m.frenchiesplus.com/Dog/code/id/' . $card_number;

        //生成二维码图片 
        $object = new \QRcode();
        $fileName = './Uploads/Qcode/' . $card_number . '.png';

        $res = $object->png($url, $fileName, $errorCorrectionLevel, $matrixPointSize, 2, false);
//        $QR = imagecreatefromstring(file_get_contents($fileName));
//
//        //输出图片    
//        imagepng($QR, $card_number . '.png');
//        imagedestroy($QR);
        return $res;
    }

    public function del() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $dog_id = I('dog_id', 0, 'intval');

        $dogs = M('Dog')->where(['user_id' => $this->user_id, 'dog_id' => $dog_id, 'is_del' => 0])->find();

        if (!$dogs || empty($dogs)) {
            $this->error('没有找到需要操作的狗卡');
        }

        $data['is_del'] = 1;

        $res = M('Dog')->where(['dog_id' => $dog_id])->save($data);

        if ($res) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败!');
        }
    }

    public function getDogCard($info, $qcode) {
//        var_dump($qcode);die;
        $info['qcode'] = scalePic($qcode, 300, 300);
//        $info['dog_name'] = '取你狗命';
//        $info['age'] = '1周岁';

        $info['xz'] = birthext($info['dog_brithday']);
//                $val['age'] = birthday($val['dog_brithday']);
        $age = birthday($info['dog_brithday']);

        $age_str = '';
        if ($age < 1) {
            $age = $age * 10;
            $age_str = $age . '个月';
        } else {
            $age = floor($age);
            $age_str = $age . '周岁';
        }
        $info['age'] = $age_str;
//        $info['card_number'] = '85220842';
//        $info['xz'] = '狗逼座';
        $info['dog_weight'] = '体重' . $info['dog_weight'] . 'kg';
//        $info['describe'] = '屌的一逼';
        $info['is_ster'] = '已绝育';
        if ($info['is_ster'] == 1) {
            $info['is_ster'] = '已绝育';
        } else {
            $info['is_ster'] = '未绝育';
        }
        $info['dog_face'] = yuan_img('.' . $info['dog_face']);


        $yuanbao_sum = M('Reward')->where(['dog_id' => $info['dog_id']])->sum('number');
        if (empty($yuanbao_sum)) {
            $yuanbao_sum = 0;
        }

        $info['yuanbao_sum'] = '打赏总值' . $yuanbao_sum . '两';

        $path = './Uploads/Qcode/share_' . $info['card_number'] . '_' . time() . '.png';
        dogcard($info, $path, $info['dog_sex']);
        return substr($path, 1);
    }

    public function test() {
        $info = M('Dog')->field('dog_id,card_number,dog_name,dog_face,dog_sex,dog_brithday,dog_weight,describe,is_ster')->select();
        foreach ($info as $val) {
            $dog_id = $val['dog_id'];
            $card_number = $val['card_number'];
            $dog_face = $val['dog_face'];
            $qcode['qcode'] = '/Uploads/Qcode/' . $card_number . '.png';

            $newFilePath = 'https://m.frenchiesplus.com/Uploads/Qcode/' . $card_number . ".png";

            $this->getQcode($newFilePath, $dog_face, $dog_id, 0);

            $qcode['share_img'] = $this->getDogCard($val, $newFilePath);

            M('Dog')->where(['dog_id' => $dog_id])->save($qcode);
        }
    }

}
